package sddz.foodmanage.fragment;


import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.text.TextUtils;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.zhy.autolayout.AutoFrameLayout;
import com.zhy.autolayout.AutoLinearLayout;

import org.json.JSONException;
import org.json.JSONObject;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import okhttp3.Request;
import sddz.foodmanage.R;
import sddz.foodmanage.activity.CreationFoodActivity;
import sddz.foodmanage.activity.LoginActivity;
import sddz.foodmanage.activity.MainNewActivity;
import sddz.foodmanage.activity.SearchNewActivity;
import sddz.foodmanage.adapter.UniversalAdapter;
import sddz.foodmanage.adapter.UniversalViewHolder;
import sddz.foodmanage.base.BaseFragment;
import sddz.foodmanage.model.ClassifyBean;
import sddz.foodmanage.model.CommodityBean;
import sddz.foodmanage.model.SelectOkBean;
import sddz.foodmanage.model.WaitListBean;
import sddz.foodmanage.utils.API;
import sddz.foodmanage.utils.GlobalParms;
import sddz.foodmanage.utils.HttpUtils;
import sddz.foodmanage.utils.SpfUtils;

import static android.app.Activity.RESULT_OK;

/**
 * @Date:2019/7/3
 * @Author:lbb 商品清单
 */
public class HomeFragment extends BaseFragment {


    @BindView(R.id.im_back)
    ImageView imBack;
    @BindView(R.id.home_sao_yi_sao)
    AutoLinearLayout homeSaoYiSao;
    @BindView(R.id.editText)
    EditText editText;
    @BindView(R.id.ll_search)
    AutoLinearLayout llSearch;
    @BindView(R.id.tv_search)
    TextView tvSearch;
    @BindView(R.id.lin_search)
    AutoLinearLayout linSearch;
    @BindView(R.id.tv_messagecontent)
    TextView tvMessagecontent;
    @BindView(R.id.tv_message)
    AutoLinearLayout tvMessage;
    @BindView(R.id.listview)
    ListView listview;
    @BindView(R.id.fragment_container)
    AutoFrameLayout fragmentContainer;
    @BindView(R.id.tv_yesterdayorder)
    TextView tvYesterdayorder;
    @BindView(R.id.tv_ok)
    TextView tvOk;
    @BindView(R.id.all_big)
    AutoLinearLayout allBig;
    private List<ClassifyBean.DataBean> list = new ArrayList<>();
    private UniversalAdapter adapter;
    private CommoditylistFragment listfragment;
    public static int mPosition;
    TextView textview;
    Unbinder unbinder;
    private int pzid;//需要传给下一个页面的品种id

    static SparseArray<CommodityBean.DataBeanX.DataBean> changelist = new SparseArray<CommodityBean.DataBeanX.DataBean>();
    //    private OnButtonClick onButtonClick;
//    FragmentTransaction fragmentTransaction;

    public HomeFragment() {
        // Required empty public constructor
    }

    @Override
    public void onDetach() {
        super.onDetach();
        try {
            Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
            childFragmentManager.setAccessible(true);
            childFragmentManager.set(this, null);

        } catch (NoSuchFieldException e) {
            throw new RuntimeException(e);
        } catch (IllegalAccessException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view = inflater.inflate(R.layout.fragment_home, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initData();
        initListent();
        view.setClickable(true);
        return view;
    }

//    @Override
//    public void onResume() {
//        super.onResume();
//        initView();
//        initData();
//        initListent();
//    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            if (SpfUtils.getUserData(mActivity).getType() == 2) {//中队
                tvYesterdayorder.setText("推荐菜单");
                tvOk.setVisibility(View.VISIBLE);
                tvMessage.setVisibility(View.VISIBLE);
                getwait(4);//获取待评论数据
//                initData();
            } else {//供应商
                tvYesterdayorder.setText("创建食材");
                tvOk.setVisibility(View.GONE);
                tvMessage.setVisibility(View.GONE);
            }
        }
    }


    private void initListent() {

        adapter = new UniversalAdapter<ClassifyBean.DataBean>(mActivity, list, R.layout.item_listleft) {

            @Override
            public void convert(UniversalViewHolder holder, int position, ClassifyBean.DataBean classifyBean) {
                textview = holder.getView(R.id.tv_classify);
                AutoLinearLayout line = holder.getView(R.id.itembackground);
                TextView redline = holder.getView(R.id.red_line);
                textview.setText(classifyBean.getName());
                if (adapter.getPosition() == position) {
                    textview.setTextColor(getResources().getColor(R.color.black));
                    line.setBackgroundColor(getResources().getColor(R.color.white));
                    redline.setVisibility(View.VISIBLE);
                } else {
                    textview.setTextColor(getResources().getColor(R.color.backgray));
                    line.setBackgroundColor(getResources().getColor(R.color.grays));
                    redline.setVisibility(View.GONE);
                }

            }
        };
        listview.setAdapter(adapter);
//

    }

    private void tihuanlistfragment(int position) {
//        Log.e("传给listfragment的str",position+"");
//        listfragment.refresh(position,1);
        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
        listfragment = new CommoditylistFragment();
        Bundle bundle = new Bundle();
        pzid = list.get(position).getId();
        Log.e("list.get(mPosition).getId()111111111111pzid", pzid + "");
        bundle.putInt(CommoditylistFragment.TAG, pzid);
        listfragment.setArguments(bundle);
        fragmentTransaction.replace(R.id.fragment_container, listfragment);
        fragmentTransaction.commit();
    }

    private void moren() {
//        FragmentTransaction fragmentTransaction = getFragmentManager().beginTransaction();
//        listfragment = new CommoditylistFragment();
//        Bundle bundle = new Bundle();
//        pzid = list.get(0).getId();
//        Log.e("list.get(mPosition).getId()111111111111pzid", pzid + "");
//        bundle.putInt(CommoditylistFragment.TAG, pzid);
//        listfragment.setArguments(bundle);
//        fragmentTransaction.replace(R.id.fragment_container, listfragment);
//        fragmentTransaction.commit();
        tihuanlistfragment(0);
        listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int position, long l) {
                //拿到当前位置
                mPosition = position;
                //即使刷新adapter
                adapter.setSelectedPosition(position);
                adapter.notifyDataSetChanged();
                tihuanlistfragment(mPosition);
            }

        });
    }

    private void initData() {
        getFenlei();
    }

    private void initView() {

        editText.setFocusable(false);
        editText.setFocusableInTouchMode(false);
        tvSearch.setVisibility(View.GONE);
        if (SpfUtils.getUserData(mActivity).getType() == 2) {//中队
            tvYesterdayorder.setText("推荐菜单");
            tvOk.setVisibility(View.VISIBLE);
            tvMessage.setVisibility(View.VISIBLE);
            getwait(4);
        } else {//供应商
            tvYesterdayorder.setText("创建食材");
            tvOk.setVisibility(View.GONE);
            tvMessage.setVisibility(View.GONE);

        }


    }


    /**
     * 获取类别列表
     */
    private void getFenlei() {
        HttpUtils.getInstance().GET(mActivity, API.getFenlei, SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {

            @Override
            public void onSuccess(String body) {
                Log.e("获取商品类别：", body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
//                        if (!jsonObject.optString("message").equals("")) {
//                            show(jsonObject.optString("message"));
//                        }
                        if (code == 200) {
                            ClassifyBean fenlei = new Gson().fromJson(body, ClassifyBean.class);
                            list.addAll(fenlei.getData());
                            adapter.notifyDataSetChanged();
                            moren();
//                            initListent();
                            Log.e("sd22222222", list.size() + "");

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            SpfUtils.savetoken(mActivity, token);
                            show(jsonObject.optString("message"));
                            getFenlei();
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            show(jsonObject.optString("message"));
                            startActivity(new Intent(mActivity, LoginActivity.class));
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {

            }
        });

    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({R.id.editText, R.id.ll_search, R.id.tv_yesterdayorder, R.id.tv_ok, R.id.tv_messagecontent})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.editText:
                MainNewActivity.a=1;
                startActivity(new Intent(mActivity, SearchNewActivity.class).putExtra("type", "false"));
                break;
            case R.id.ll_search://点击搜索框，跳转到搜索页面
                startActivity(new Intent(mActivity, SearchNewActivity.class).putExtra("type", "false"));
                break;
            case R.id.tv_yesterdayorder:
                if (tvYesterdayorder.getText().toString().equals("创建食材")) {
                    startActivityForResult(new Intent(mActivity, CreationFoodActivity.class).putExtra("status", "true"), 1);

                } else if (tvYesterdayorder.getText().toString().equals("推荐菜单")) {
                    startActivity(new Intent(mActivity, SearchNewActivity.class).putExtra("type", "true")
                    );
                }
                break;
            case R.id.tv_ok://选好了
                getSelect();
                break;
            case R.id.tv_messagecontent:// 点击消息
                Log.e("点击消息", "111");
                SpfUtils.setwaitpl(mActivity, "有");
                GlobalParms.sChangeFragment.changge(2);
                break;
        }
    }

    /**
     * 选好了
     */
    private void getSelect() {
        baseDialog.show();
        final SelectOkBean selectok = new SelectOkBean();
                    List<SelectOkBean.DataBean> selectoklist = new ArrayList<>();
                    if (changelist.size() > 0) {
                        for (int q = 0; q < changelist.size(); q++) {
                            SelectOkBean.DataBean databean = new SelectOkBean.DataBean();
                            databean.setId(changelist.get(changelist.keyAt(q)).getId());
                            databean.setAmount(changelist.get(changelist.keyAt(q)).getNum() + "");
                            selectoklist.add(databean);
                        }
                        List<SelectOkBean.DataBean> newlist = rMList(selectoklist);
                        for (int q = 0; q < newlist.size(); q++) {
                            if (newlist.get(q).getAmount().equals("0.0")) {
                                newlist.remove(q);
                            }
                        }
//                        Log.e("JSON.toJSONString(newlist)",JSON.toJSONString(newlist));
                        if (newlist.size() > 0) {
                            selectok.setData(newlist);
//                            Log.e("JSON.toJSONString(selectok)",JSON.toJSONString(selectok));
//                    baseDialog.show();
                            HttpUtils.getInstance().POST(mActivity, API.getselectok, JSON.toJSONString(selectok), SpfUtils.gettoken(mActivity).toString(), new HttpUtils.OnOkHttpCallback() {
                                @Override
                                public void onSuccess(String body) {
                                    Log.e("选好了上传结果", body);
                                    baseDialog.dismiss();
                                    if (!TextUtils.isEmpty(body)) {
                                        try {
                                            JSONObject jsonObject = new JSONObject(body);
                                            int code = jsonObject.optInt("status_code");
                                            if (code == 200) {
                                                changelist.clear();//只有在选好了数据 上传成功后，清空数据
                                                tihuanlistfragment(mPosition);
                                                GlobalParms.sChangeFragment.changge(1);
                                            } else if (code == 210) {
                                                String token = jsonObject.optJSONObject("data").optString("token");
                                                SpfUtils.savetoken(mActivity, token);
                                                getSelect();
                                            } else if (code == 401) {
                                                show(jsonObject.optString("message"));
                                                SpfUtils.setLogin(mActivity, false);
                                                startActivity(new Intent(mActivity, LoginActivity.class));
                                                mActivity.finish();
                                            }
                                        } catch (JSONException e) {
                                            e.printStackTrace();
                                        }
                                    }
                                }

                                @Override
                                public void onError(Request error, Exception e) {
                                    baseDialog.dismiss();
                                    show("访问数据失败，请稍后重试");
                                }
                            });
                        } else {
                            if(baseDialog!=null){
                                baseDialog.dismiss();
                            }

                            show("请选择商品");
                        }
                    } else {
                        if(baseDialog!=null){
                            baseDialog.dismiss();
                        }
                        show("请选择商品");
                    }
    }


    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);

        if (requestCode == 1 && resultCode == RESULT_OK) {//创建页面返回的，需要刷新数据
            tihuanlistfragment(mPosition);
        }
    }

    //获取待核实待评论数据 type 待配送 2 待核实 3 待评论 4
    private void getwait(final int type) {
        Map<String, Integer> map = new HashMap<>();
        map.put("type", type);
//        baseDialog.show();
        HttpUtils.getInstance().POST(mActivity, API.getwaitlist, JSON.toJSONString(map), SpfUtils.gettoken(mActivity), new HttpUtils.OnOkHttpCallback() {
            @Override
            public void onSuccess(String body) {
//                baseDialog.dismiss();
                Log.e("aaaaaaaaaaaaaaaaaaa获取的待评论" + type, body);
                if (!TextUtils.isEmpty(body)) {
                    try {
                        JSONObject jsonObject = new JSONObject(body);
                        int code = jsonObject.optInt("status_code");
                        if (code == 200) {
                            WaitListBean waitListBean = new Gson().fromJson(body, WaitListBean.class);
                            if (waitListBean.getData().size() > 0) {
                                tvMessagecontent.setText("有" + waitListBean.getData().size() + "条待评论消息");
                            } else {
                                tvMessagecontent.setText("暂无待评论消息");
                            }

                        } else if (code == 210) {
                            String token = jsonObject.optJSONObject("data").optString("token");
                            Log.e("33333333", token);
                            SpfUtils.savetoken(mActivity, token);
                            getwait(4);
                        } else if (code == 401) {
                            SpfUtils.setLogin(mActivity, false);
                            startActivity(new Intent(mActivity, LoginActivity.class));
                            mActivity.finish();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                    }
                }

            }

            @Override
            public void onError(Request error, Exception e) {
//                baseDialog.dismiss();
                show("访问数据失败，请稍后重试");
            }
        });

    }

    private Set<Integer> setSum;

    // 去掉重复数据
    private ArrayList rMList(List<SelectOkBean.DataBean> al) {
        setSum = new HashSet<Integer>();
        ArrayList<SelectOkBean.DataBean> newList = new ArrayList();
        if (al != null) {
            for (Iterator iter = al.iterator(); iter.hasNext(); ) {
                SelectOkBean.DataBean element = (SelectOkBean.DataBean) iter.next();
                if (setSum.add(element.getId()))
                    newList.add(element);
            }
        }
        return newList;
    }
}
